/**
 * 
 */
package info.niwota.ezb;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public class WebshotInstallActivity extends Activity {

	private static final String TAG = "WebshotInstallActivity";

	private static final String INSTALL_PKG = "market://search?q=pname:info.niwota.webshot";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		if (Debug.DEBUG) {
			Log.d(TAG, "onCreate " + savedInstanceState);
		}
		showDownload();
	}

	private void showDownload() {
		final CharSequence title = "Webshot by Li, Qiang";
		final CharSequence msg = "Webshot (free) is required to manage web based mobile boarding pass (HTML). Download Webshot from Android Market?";
		final CharSequence yes = "Yes";
		final CharSequence no = "No";
		//
		final Context ctx = this;
		AlertDialog d = new AlertDialog.Builder(ctx).create();
		d.setIcon(android.R.drawable.ic_dialog_info);
		d.setTitle(title);
		d.setMessage(msg);
		d.setButton(yes, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					Uri uri = Uri.parse(INSTALL_PKG);
					Intent i = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(i);
				} catch (Exception e) {
					Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT);
				}
				finish();
				return;
			}
		});
		d.setButton2(no, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(ctx, "Download cancelled", Toast.LENGTH_SHORT);
				finish();
				return;
			}
		});
		d.show();
	}
	
	public static boolean isWebshotAvailable(Context ctx) {
		final PackageManager packageManager = ctx.getPackageManager();
		final Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		i.setClassName("info.niwota.webshot", "info.niwota.webshot.WebPickActcivity");
		List<ResolveInfo> l = packageManager.queryIntentActivities(i,
				PackageManager.MATCH_DEFAULT_ONLY);
		return (l.size() > 0);
	}
}
